package com.zh.tea.web;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zh.tea.entity.User;
import com.zh.tea.service.UserService;
import com.zh.tea.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	UserService us = new UserServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=utf-8");// 此句话必须在创建out之前
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		String opt = request.getParameter("opt");
		if("login".equals(opt)) {
			String name = request.getParameter("name");
			String pwd = request.getParameter("textfield2");
			User user = us.login(name, pwd);
			if(user!=null) {
				session.setAttribute("User",user);
			 	out.print("<script>alert('登陆成功!');location.href='index.jsp'</script>");
			}else {
				out.print("<script>alert('用户名或密码错误，无账号请点击注册!');location.href='index.jsp'</script>");
			}
			
		}
		if("register".equals(opt)) {
			String name = request.getParameter("name");
			String pwd = request.getParameter("textfield2");
			String rname = request.getParameter("rname");
			String email = request.getParameter("email");
			String lx = request.getParameter("lx");
			String cno = request.getParameter("cno");
			String address = request.getParameter("address");
			String phone = request.getParameter("phone");
			User user = new User();
			user.setPassname(name);
			user.setPassword(pwd);
			user.setRealname(rname);
			user.setEmail(email);
			user.setCerttype(lx);
			user.setCertno(cno);
			user.setAddress(address);
			user.setPhone(phone);
			int a = us.addUser(user);
			if(a>0) {
			 	out.print("<script>alert('注册成功!');location.href='login1.jsp'</script>");
			}else {
				out.print("<script>alert('注册失败!');location.href='register.jsp'</script>");
			}
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
